package io.awen.common.utils;

//import javafx.application.Application;
//import javafx.stage.Stage;

import io.awen.modules.sign.entity.SignContainerEntity;
import io.awen.modules.sign.entity.SignSinkEntity;

import java.util.List;

public class DistanceUtil {
    private static final double EARTH_RADIUS = 6371.0; // 地球半径，单位：千米

    public static Long getNearestContainerId(double lon, double lat, List<SignContainerEntity> containers) {
        double minDistance = Double.MAX_VALUE;
        Long nearestContainerId = null;
        for (SignContainerEntity container : containers) {
            double distance = getDistance(lon, lat, container.getLon(), container.getLat());
            if (distance < minDistance && distance <= 0.05) {
                minDistance = distance;
                nearestContainerId = container.getId();
            }
        }
//        System.out.println("minDistance: " + minDistance);
        return nearestContainerId;
    }

    public static Long getNearestSinkId(double lon, double lat, List<SignSinkEntity> sinks) {
        double minDistance = Double.MAX_VALUE;
        Long nearestSinkId = null;
        for (SignSinkEntity sink : sinks) {
            double distance = getDistance(lon, lat, sink.getLon(), sink.getLat());
            if (distance < minDistance && distance <= 0.09) {
                minDistance = distance;
                nearestSinkId = sink.getId();
            }
        }
        return nearestSinkId;
    }

    public static double getDistance(double lon1, double lat1, double lon2, double lat2) {
        double radLat1 = Math.toRadians(lat1);
        double radLat2 = Math.toRadians(lat2);
        double a = radLat1 - radLat2;
        double b = Math.toRadians(lon1) - Math.toRadians(lon2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s *= EARTH_RADIUS;
        return s;
    }
}
